package com.jms.boot.config;

import com.jms.framework.beans.annotation.Configuration;
import com.jms.framework.config.JmsAbstractConfig;
import com.jms.framework.exception.DataNotLegitimateException;
import com.jms.framework.exception.PropertyAlreadySetException;
import com.jms.tools.util.AnnotationUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


public class JmsBootConfig extends JmsAbstractConfig {

    private static final Logger logger = LogManager.getLogger(JmsBootConfig.class);
    private volatile static JmsBootConfig config;

    private JmsBootConfig() {
    }

    public static JmsBootConfig getInstance() {
        if (config == null) {
            synchronized (JmsBootConfig.class) {
                if (config == null) {
                    config = new JmsBootConfig();
                }
            }
        }
        return config;
    }

    public JmsBootConfig setConfigLocation(String configLocation) {
        if (this.configLocation != null) {
            throw new PropertyAlreadySetException(String.class, "configLocation");
        }
        this.configLocation = configLocation;
        return this;
    }

    public JmsBootConfig setConfigName(String configName) {
        if (this.configName != null) {
            throw new PropertyAlreadySetException(String.class, "configName");
        }
        this.configName = configName;
        return this;
    }

    public JmsBootConfig setConfigType(String configType) {
        if (this.configType != null) {
            throw new PropertyAlreadySetException(String.class, "configType");
        }
        this.configType = configType;
        return this;
    }

    public JmsBootConfig setBootClass(Class<?> bootClass) {
        if (this.bootClass != null) {
            throw new PropertyAlreadySetException(bootClass, "configClass");
        }
        if (AnnotationUtils.hasAnnotation(bootClass, Configuration.class)) {
            this.bootClass = bootClass;
        } else {
            throw new DataNotLegitimateException("The config class must be annotated with @Configuration");
        }
        return this;
    }

    @Override
    public void initConfig() {
        logger.info("JmsBootConfig initConfig start.");
        super.initConfig();
        logger.info("JmsBootConfig initConfig end.");
    }

    @Override
    public void destroy() {
        logger.info("JmsBootConfig destroy start.");
        super.destroy();
        logger.info("JmsBootConfig destroy end.");
    }

    @Override
    public void resolveConfig() {
        logger.info("JmsBootConfig resolveConfig start.");
        logger.info("JmsBootConfig resolveConfig from: {}", configLocation == null ? configName + "." + configType : configLocation);
        super.resolveConfig();
        logger.info("JmsBootConfig resolveConfig end.");
    }
}
